package com.sf.osms.dep.quartz;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.sf.novatar.cluster.IKeepAliveAndLockResolver;
import com.sf.osms.dep.biz.ICommonServiceBiz;
import com.sf.osms.dep.domain.Router;
import com.sf.osms.dep.processor.util.CollectionUtil;
import com.sf.osms.dep.processor.util.ExceptionUtils;
import com.sf.osms.dep.processor.util.RouterConstants;
import com.sf.osms.dep.processor.util.SwitchUtils;
import com.sf.osms.dep.processor.util.WebserviceUtil;

public class DepRouteRegisterToFVPJob {
	private static Logger logger = LoggerFactory.getLogger(DepRouteRegisterToFVPJob.class);
	
	public static final String LOCK_NAME = "dep_router_register";
	private static final int STATUS = 0;
	
	@Autowired
	private  IKeepAliveAndLockResolver clusterSync;
	
	@Autowired
	private ICommonServiceBiz commonRouteService;
	
	/***
     * 路由节点定时任务
     */
	public void job()
	{ 
		if(clusterSync.isLockedFor(LOCK_NAME)){
			return;
		}
		boolean lock = clusterSync.getLockFor(LOCK_NAME);
		if(!lock){
			return;
		} 
		logger.info("------------>DepRouteUploadJob start");

		try {
			if(SwitchUtils.getSwithBySystemName(SwitchUtils.DEP_TO_FVP_REGISTER)){
				routeRegisterToFvp();
			}
		} catch (Exception e) {
			logger.error("------------>DepRouteUploadJob run error!"+e.getMessage()); 
			logger.error(e.getMessage(), e);
		} 	
		clusterSync.releaseLockFor(LOCK_NAME);  
		
		logger.info("------------>DepRouteUploadJob End");
	}  
	
	
	private void routeRegisterToFvp(){
 		List<Router> routers = commonRouteService.queryRouterByStatus(STATUS);
		if(CollectionUtil.isEmpty(routers)){
 			return;
		}
		List<String> sfwaybills = new ArrayList<String>();
		for (Router router : routers) {
			sfwaybills.add(router.getSfWaybill());
		}
		boolean result = false;
		try {
			result = WebserviceUtil.registerRouterOnKafka(sfwaybills);
		} catch (Exception e) {
			logger.error("*******invoke register fvp router occur exception " + ExceptionUtils.getExceptionStackString(e));
		}
		
		if(result){
			for (Router router : routers) {
				router.setStatus(RouterConstants.FVP_RESIGER_ROUTER_SUCCESS);
				router.setStatusDt(new Date());
			}
			commonRouteService.updateRoute(routers);
			logger.info("******invoke register fvp router successfully " + routers.toString());
		}else{
			logger.error("********invoke register fvp router fail " + routers.toString());
		}
		
		
		
	}
}
